<template>
  <div>
    <!-- 顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">活动管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索添加用户 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 用户搜索 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList2"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList2"
            >
            </el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userlist" style="width: 100%" border class="userform">
        <el-table-column type="index" label="id"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatusChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 用户编辑操作 -->
            <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="showDialogVisible(scope.row.id)"></el-button>
            <!-- 删除操作弹框 -->
            <template>
              <!-- 删除操作 -->
              <el-button type="danger" @click="open(scope.row.id)" icon="el-icon-delete" circle size="mini"></el-button>
            </template>
            <!-- 用户角色编辑 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle size="mini" @click="setRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 注册用户弹出框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      @closed="formClose"
    >
      <!-- 添加用户表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户弹出框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色弹出框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="roleDialogClosed"
    >
      <div class="set-role">
        <p><el-divider>当前用户：<el-tag type="warning">{{roleInfo.username}}</el-tag></el-divider></p>
        <p><el-divider>当前角色：<el-tag type="warning">{{roleInfo.role_name}}</el-tag></el-divider></p>
        <p>
          <el-divider>
            <el-select v-model="selectRoleId" placeholder="请选择" ref="selectRef">
              <el-option
                v-for="item in roleLists"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-divider>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确邮箱'))
    }
    return {
      roleDialogVisible: false,
      roleLists: [],
      // ^select以选中的id
      selectRoleId: [],
      queryInfo: { query: '', pagenum: 1, pagesize: 5 },
      userlist: [],
      total: 0,
      dialogVisible: false,
      editDialogVisible: false,
      editForm: {},
      roleInfo: {},
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在3～10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名长度在6～15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // console.log(this.queryInfo.pagesize)
    const num = sessionStorage.getItem('size')
    if (num) {
      this.queryInfo.pagesize = parseInt(num)
    } else {
      this.queryInfo.pagesize = 5
    }
    this.getUserList()
    console.log(this.$route)
    // console.log(parseInt(num))
  },
  methods: {
    getUserList () {
      this.$http.getUsers(this.queryInfo)
        .then(resp => {
          const { data } = resp
          // console.log(data)
          if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
          this.userlist = data.data.users
          this.total = data.data.total
          // console.log(this.total)
        })
      // this.$http.getUsers()
    },
    // ^搜索用户
    getUserList2 () {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      sessionStorage.setItem('size', newSize)
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // ^用户状态
    userStatusChanged (row) {
      // console.log(row)
      this.$http.changUserState(row.id, row.mg_state)
        .then(resp => {
          const { data } = resp
          // console.log(data)
          if (data.meta.status !== 200) {
            row.mg_state = !row.mg_state
            return this.$message.error('更新用户状态失败')
          } else {
            this.$message.success('更新用户状态成功')
          }
        })
    },
    // ^监听添加用户弹出框关闭事件
    formClose () {
      this.$refs.addFormRef.resetFields()
      // console.log(this.$refs.addFormRef)
    },
    // ^添加用户
    addUser () {
      this.$refs.addFormRef.validate(vaild => {
        if (!vaild) return vaild
        // &发起添加用户请求
        this.$http.addUser(this.addForm)
          .then(resp => {
            // console.log(this.addForm.username)
            // console.log(resp)
            const { data } = resp
            if (data.meta.status !== 201) {
              this.$message.error('添加用户失败')
            }
            this.$message.success('添加用户成功')
            this.dialogVisible = false
            this.getUserList()
          })
      })
    },
    // ^修改用户按钮
    showDialogVisible (id) {
      // console.log(id)
      this.$http.getUsersInfo(id)
        .then(resp => {
          const { data } = resp
          // console.log(data)
          if (data.meta.status !== 200) {
            return this.$message.error('获取数据失败')
          }
          this.editForm = data.data
          this.editDialogVisible = true
          // console.log(this.editForm)
        })
    },
    // ^修改用户弹窗关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // ^确定修改用户信息按钮
    editUserInfo () {
      this.$refs.editFormRef.validate(vaild => {
        // console.log(vaild)
        if (vaild) {
          this.$http.putEditUserInfo(this.editForm.id, this.editForm.email, this.editForm.mobile)
            .then(resp => {
              const { data } = resp
              if (data.meta.status !== 200) {
                return this.$message.error('更新用户信息失败')
              }
              this.$message.success('更新用户信息成功')
              this.getUserList()
              this.editDialogVisible = false
            })
        }
      })
    },
    // ^确认删除用户弹窗
    open (id) {
      const that = this
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.$http.deleteUser(id)
          .then(resp => {
            if (resp.data.meta.status !== 200) {
              return this.$message.error('删除用户失败')
            }
            this.getUserList()
            that.getUserList()
          })
        // console.log(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // ^Select修改角色弹窗
    setRoleDialog (role) {
      this.roleInfo = role
      // console.log(this.roleInfo)
      this.$http.getRolesList()
        .then(resp => {
          // console.log(resp)
          const { data } = resp
          this.roleLists = data.data
          // console.log(resp)
        })
      this.roleDialogVisible = true
    },
    // ^修改角色
    setRole () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择用户角色')
      }
      // console.log(this.roleInfo)
      this.$http.setRole(this.roleInfo.id, this.selectRoleId)
        .then(resp => {
          // console.log(resp.data)
          this.$message.success('分配角色成功')
          this.getUserList()
          this.roleDialogVisible = false
        })
      // console.log(this.srlectRoleId)
    },
    roleDialogClosed () {
      this.selectRoleId = ''
      this.roleInfo = {}
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-card {
    margin-top: 15px;
    .userform {
      margin: 15px 0;
      font-size: 12px;
    }
  }
  .set-role {
    p {
      display: block;
      padding: 1px 27px;
    }
  }
</style>
